package com.zx.crowdfunding.handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.zx.crowdfunding.constant.CrowdFundingConstant;
import com.zx.crowdfunding.entity.po.MemberPO;
import com.zx.crowdfunding.service.api.MemberService;
import com.zx.crowdfunding.util.ResultEntity;

/**
 * 会员 - Handler - 远程接口实现
 * @author 郑雪
 * @date 2021-12-29
 */
@RestController
public class MemberProviderHandler {
	
	/**
	 * 会员Service接口
	 */
	@Autowired
	private MemberService memberService;

	/**
	 * 通过登录账号获取会员PO对象
	 * @param loginacct 登录账号
	 * @return 携带MemberPO对象的ResultEntity对象
	 */
	@RequestMapping("/get/memberpo/by/login/acct/remote")
	public ResultEntity<MemberPO> getMemberPOByLoginAcctRemote(@RequestParam("loginacct") String loginacct){
		
		try {
			
			// 1.调用本地Service完成查询
			MemberPO memberPO = memberService.getMemberPOByLoginAcct(loginacct);
			
			// 2.如果没有抛异常，则返回成功的结果
			return ResultEntity.successWithData(memberPO);
		} catch (Exception e) {
			e.printStackTrace();
			
			// 如果捕获到异常，则返回失败的结果
			return ResultEntity.failed(e.getMessage());
		}
		
	}
	
	/**
	 * 添加会员
	 * @param memberPO 会员PO对象
	 * @return ResultEntity对象
	 */
	@RequestMapping("/save/member/remote")
	public ResultEntity<String> saveMemberRemote(@RequestBody MemberPO memberPO){
		
		try {
			
			memberService.saveMember(memberPO);
			
			return ResultEntity.successWithoutData();
			
		} catch (Exception e) {
			
			// 如果是违反唯一约束的异常
			if(e instanceof DuplicateKeyException){
				return ResultEntity.failed(CrowdFundingConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
			}
						
			return ResultEntity.failed(e.getMessage());
		}
		
	}

}
